import 'dart:async';
import 'package:flutter/material.dart';
import 'package:yysk_app/utils/colors.dart';
import 'package:yysk_app/utils/helper.dart';

class CountdownTimer extends StatefulWidget {
  final dynamic expireTime;
  final Color fontColor;
  final double fontSize;
  final bool showHours; // 新增：是否显示小时
  final FontWeight? fontWeight;
  final VoidCallback? onPressed;

  const CountdownTimer({
    super.key,
    required this.expireTime,
    this.fontColor = AppColors.fontColor,
    this.fontSize = 14,
    this.showHours = true, // 默认显示小时
    this.fontWeight = FontWeight.bold,
    this.onPressed,
  });

  @override
  // ignore: library_private_types_in_public_api
  _CountdownTimerState createState() => _CountdownTimerState();
}

class _CountdownTimerState extends State<CountdownTimer> {
  late Timer _timer;
  int _remainingTime = 0;
  bool _showHours = true;

  @override
  void initState() {
    super.initState();
    if (widget.expireTime != null) {
      _startTimer();
    }
    _showHours = widget.showHours;
  }

  void _startTimer() {
    // 计算剩余时间（秒）
    final now = DateTime.now().millisecondsSinceEpoch;
    final difference = widget.expireTime - now;

    setState(() {
      if (difference > 0) {
        _remainingTime = difference ~/ 1000;

        // 自动判断是否需要显示小时（如果小于1小时且showHours为false，则隐藏小时）
        if (!widget.showHours && _remainingTime < 3600) {
          _showHours = false;
        } else {
          _showHours = true;
        }
      } else {
        _remainingTime = 0;
      }
    });

    // 启动定时器，每秒更新一次
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      setState(() {
        if (_remainingTime > 0) {
          _remainingTime--;

          // 动态更新小时显示状态（当时间小于1小时时自动隐藏小时）
          if (!widget.showHours && _remainingTime < 3600) {
            _showHours = false;
          }
        } else {
          timer.cancel();
          widget.onPressed?.call();
        }
      });
    });
  }

  @override
  void didUpdateWidget(CountdownTimer oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.expireTime != widget.expireTime) {
      _timer.cancel();
      _startTimer();
    }
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  // 格式化时间为 HH:mm:ss 或 mm:ss
  String _formatTime() {
    if (_remainingTime <= 0) return _showHours ? "00:00:00" : "00:00";

    final hours = _remainingTime ~/ 3600;
    final minutes = (_remainingTime % 3600) ~/ 60;
    final seconds = _remainingTime % 60;

    if (_showHours) {
      return '${hours.toString().padLeft(2, '0')}:'
          '${minutes.toString().padLeft(2, '0')}:'
          '${seconds.toString().padLeft(2, '0')}';
    } else {
      return '${minutes.toString().padLeft(2, '0')}:'
          '${seconds.toString().padLeft(2, '0')}';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      _formatTime(),
      style: TextStyle(
        fontSize: widget.fontSize.px,
        fontWeight: widget.fontWeight,
        color: widget.fontColor,
      ),
    );
  }
}
